const Base = require('./base.js');
const moment = require('moment');
const exportExcel = require('../util/exportExcel');
module.exports = class extends Base {
  async postAction() {
    const model = this.model('poi_search_employ');
    const insertId = await model.add(
      {
        poi_name: this.post('poi_name'),
        floor_name: this.post('floor_name'),
        building_name: this.post('building_id'),
        device_id: this.post('device_id'),
        use_time: moment().format('YYYY-MM-DD HH:mm:ss')
      });
    if (insertId > 0) {
      return this.success('', '上传数据成功');
    } else {
      return this.fail(100, '上传数据失败');
    }
  }

  indexAction() {
    return this.display();
  }

  async listAction() {
    const model = this.model('poi_search_employ');
    const dateCal = this.service('datecal');
    const dates = dateCal.getAllDates(this.post('startDate'),
      this.post('endDate'), this.post('type'));
    const counts = await model.listData(
      this.post('bid'),
      this.post('fid'),
      this.post('type'),
      this.post('startDate'),
      this.post('endDate'));

    const tops = await model.topData(
      this.post('bid'),
      this.post('fid'),
      this.post('type'),
      this.post('startDate'),
      this.post('endDate'));

    const cnts = [];
    dates.forEach(function (element, sameElement, set) {
      for (let j = 0; j < counts.length; j++) {
        if (element === counts[j].days) {
          cnts.push(counts[j].count);
          break;
        }
        if (j === counts.length - 1) {
          cnts.push(0);
        }
      }
    });

    return this.success({'count': cnts, 'dates': dates, 'tops': tops});
  }

  async exportExcelAction() {
    const model = this.model('poi_search_employ');
    const dateCal = this.service('datecal');
    const dates = dateCal.getAllDates(this.get('startDate'),
      this.get('endDate'), this.get('type'));
    const counts = await model.listData(
      this.get('bid'),
      this.get('fid'),
      this.get('type'),
      this.get('startDate'),
      this.get('endDate'));

    const cnts = [];
    dates.forEach(function (element, sameElement, set) {
      for (let j = 0; j < counts.length; j++) {
        if (element === counts[j].days) {
          cnts.push(counts[j].count);
          break;
        }
        if (j === counts.length - 1) {
          cnts.push(0);
        }
      }
    });

    const data = {'cnts': cnts, 'dates': dates};
    const row = [];
    for (let i = 0; i < data.cnts.length; i++) {
      const temp = [data.dates[i] + '', data.cnts[i] + ''];
      row.push(temp);
    }

    const header = [
      {caption: '日期', type: 'string'},
      {caption: 'POI搜索次数', type: 'string'}
    ];
    this.ctx.res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    this.ctx.res.setHeader('Content-Disposition', 'attachment; filename=' + 'AZ_poi_search_employ.xlsx');
    this.ctx.res.end(exportExcel.exportExcel(header, row), 'binary');
  }
};
